package com.cskaoyan.controller.coupon.admin;


import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.Coupon;
import com.cskaoyan.bean.CouponUser;
import com.cskaoyan.bean.ListData;
import com.cskaoyan.bean.coupon.CreateCouponBO;
import com.cskaoyan.bean.coupon.DeleteCouponBO;
import com.cskaoyan.service.coupon.admin.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("/admin/coupon")
public class CouponController {

    @Autowired
    CouponService couponService;

    /**
     *  status 需要额外处理
     *      更新：status要显示到前台。status 和微信小程序的status含义不同，每次访问数据库都应自动更新status的数值
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param name
     * @param type
     * @param status 0 ：正常  1：已过期  2：已下架
     * @return
     */
    @RequestMapping("/list")
    public BaseRespVo list(String page, String limit, String sort, String order, String name, String type,Integer status){
//        try {
            ListData<Coupon> list = couponService.list(page, limit, sort, order, name, type,status);
            return BaseRespVo.ok(list,"成功");
//        }catch (Exception e){
//            return BaseRespVo.fail("failed ,try again ");
//        }
    }

    /**
     * 此方法为假删除。
     * 如果从数据库彻底删除了此优惠券，而用户已经领取，且不能删除用户的优惠券，则用户下单时不能获得折扣信息
     * @param deleteCouponBO
     * @return
     */
    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody DeleteCouponBO deleteCouponBO){
        boolean delete = couponService.delete(deleteCouponBO.getId());
        if (delete){
            return BaseRespVo.ok();
        }else {
            return BaseRespVo.fail("delete fail,try again");
        }
    }

    /**
     * 此方法需要事务
     * 另外，需要返回刚刚插入的优惠券信息
     * 如果是兑换码，则需要生成兑换码，返回给前端
     * @param createCouponBO
     * @return
     */
    @RequestMapping("create")
    @Transactional
    public BaseRespVo create(@RequestBody CreateCouponBO createCouponBO){
        BaseRespVo baseRespVo = checkCreateParams(createCouponBO);
        if (baseRespVo != null){
            return baseRespVo;
        }
        boolean b = couponService.create(createCouponBO);
        if (b){
            int i = couponService.lastInsertId();
            Coupon coupon = couponService.selectByPrimaryKey(i);
            coupon.setCode("未知");
            return BaseRespVo.ok(coupon,"成功");//直接把Coupon对象传给前端会不会报错？和json字符串的字段没有对应上，不会报错。
        }else {
            return BaseRespVo.fail("create error,try again");
        }
    }

    /**
     * @RequestBody 不能少，异常：空指针
     * @param coupon
     * @return
     */
    @RequestMapping("update")
    public BaseRespVo update(@RequestBody Coupon coupon){
        BaseRespVo baseRespVo = checkUpdateParams(coupon);
        if (baseRespVo != null){
            return baseRespVo;
        }
        boolean update = couponService.update(coupon);
        System.out.println("coupon.getId() = " + coupon.getId());
        if (update){
            return BaseRespVo.ok();
        }else {
            return BaseRespVo.fail("update fail ,try again ");
        }
    }



    /**
     *
     * @param page
     * @param limit
     * @param userId
     * @param status 0：未使用 1：已使用 2：已过期 3：已下架/已删除
     * @param couponId
     * @param sort
     * @param order
     * @return
     */
    @RequestMapping("listuser")
    public BaseRespVo listUser(String page, String limit,String userId,String status, String couponId, String sort, String order){
        ListData<CouponUser> listData = couponService.listUser(page, limit, userId, status, couponId, sort, order);
        if (listData != null){
            return BaseRespVo.ok(listData,"成功");
        }else {
            return BaseRespVo.ok("failed ,try again ");
        }
    }

    @RequestMapping("read")
    public BaseRespVo read(String id){
        Coupon coupon = couponService.selectByPrimaryKey(Integer.valueOf(id));
        if (coupon != null){
            return BaseRespVo.ok(coupon,"成功");
        }else {
            return BaseRespVo.fail("failed,try again");
        }
    }

    /**
     * 检验用户输入的参数是否合法
     * @param createCouponBO
     * @return
     */
    private BaseRespVo checkCreateParams(CreateCouponBO createCouponBO){
//        boolean number = TestParam.isNumber(createCouponBO.getTotal());
//        boolean number1 = TestParam.isNumber(createCouponBO.getDiscount());
//        boolean number2 = TestParam.isNumber(createCouponBO.getMin());
//        boolean number3 = TestParam.isNumber(createCouponBO.getDays());
//        boolean number4 = TestParam.isNumber(createCouponBO.getLimit());
        boolean days = Integer.valueOf(createCouponBO.getDays()) > 0 ? true:false;
        boolean discount = (createCouponBO.getDiscount().compareTo(BigDecimal.ZERO)> 0) ? true:false;
        boolean total = Integer.valueOf(createCouponBO.getTotal())> 0 ? true:false;
        boolean min = (createCouponBO.getMin().compareTo(BigDecimal.ZERO)> 0) ? true:false;
        boolean limit = Integer.valueOf(createCouponBO.getLimit())> 0 ? true:false;

        if (! limit)
            return BaseRespVo.fail("创建失败：每人限领数量必须大于0 ");
        if (! min)
            return BaseRespVo.fail("创建失败：最低消费必须大于0 ");
        if (! total)
            return BaseRespVo.fail("创建失败：总数必须大于0 ");
        if (! discount)
            return BaseRespVo.fail("创建失败：折扣必须大于0 ");
        if ((createCouponBO.getTimeType().intValue() == 1)){
            boolean days2 = createCouponBO.getEndTime().getTime() > createCouponBO.getStartTime().getTime();
            if (! days2){
                return BaseRespVo.fail("结束时间应该比开始时间晚！");
            }
        }

        if ((createCouponBO.getTimeType().intValue() == 0) &&(! days))
            return BaseRespVo.fail("创建失败：天数必须大于0 ");
        if (! (createCouponBO.getMin().compareTo(createCouponBO.getDiscount()) == 1))
            return  BaseRespVo.fail("创建失败：最低消费必须大于折扣金额");
        return null;
    }

    private BaseRespVo checkUpdateParams(Coupon coupon) {
//        boolean number = TestParam.isNumber(coupon.getTotal());
//        boolean number1 = TestParam.isNumber(coupon.getDiscount());
//        boolean number2 = TestParam.isNumber(coupon.getMin());
//        boolean number3 = TestParam.isNumber(coupon.getDays());
//        boolean number4 = TestParam.isNumber(coupon.getLimit());
        boolean days = Integer.valueOf(coupon.getDays()) > 0 ? true:false;
        boolean discount = coupon.getDiscount().compareTo(BigDecimal.ZERO) > 0 ? true:false;
        boolean total = Integer.valueOf(coupon.getTotal())> 0 ? true:false;
        boolean min = coupon.getMin().compareTo(BigDecimal.ZERO) > 0 ? true:false;
        boolean limit = Integer.valueOf(coupon.getLimit())> 0 ? true:false;

        if (! limit)
            return BaseRespVo.fail("创建失败：每人限领数量必须大于0 ");
        if (! min)
            return BaseRespVo.fail("创建失败：最低消费必须大于0 ");
        if (! total)
            return BaseRespVo.fail("创建失败：总数必须大于0 ");
        if (! discount)
            return BaseRespVo.fail("创建失败：折扣必须大于0 ");
        if ((coupon.getTimeType().intValue() == 1)){
            boolean days2 = coupon.getEndTime().getTime() > coupon.getStartTime().getTime();
            if (! days2){
                return BaseRespVo.fail("结束时间应该比开始时间晚！");
            }
        }

        if ((coupon.getTimeType().intValue() == 0) &&(! days))
            return BaseRespVo.fail("创建失败：天数必须大于0 ");
        return null;
    }
}
